package com.yatush.backstage.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

public abstract class BaseAction extends SimpleFormController {

	/** Logger for this class and subclasses */
	protected final Log logger = LogFactory.getLog(getClass());
	private static final String COMMAND_NAME = "bean";

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws ServletException, InstantiationException,
			IllegalAccessException, ClassNotFoundException {
		Bean bean = (Bean) Class.forName(
				this.getClass().getPackage().getName()
						+ "."
						+ this.getClass().getSimpleName()
								.replaceAll("Action$", "Bean")).newInstance();
		loadData(bean);
		System.out.println("--->" + bean.getClass().getCanonicalName());
		setCommandName(COMMAND_NAME);
		setCommandClass(bean.getClass());
		return bean;
	}

	@Override
	public ModelAndView onSubmit(Object bean) throws ServletException {
		logger.info("sending to saveForm with " + bean.toString());
		String saveResult = saveForm((Bean) bean);
		if (saveResult == null) {
			// stay here
			return null;
		} else {
			return new ModelAndView(new RedirectView(getSuccessView()));
		}
	}

	protected abstract void loadData(Bean newBean);

	protected abstract String saveForm(Bean command);
}
